var MAIN_CONSOLE = "console_manager" , PLAT_FORM = "platform";
var jsList = {} , old_new_form_relative = {} , param_pub_kv = {};
var target_kv = {'_blank' : '弹出新页面' , '_panel' : '统一窗口链接' , 'default' : '默认功能区'};
var detail_row_css = [['plat_table_double','plat_table_double_content'] , ['plat_table_signal','plat_table_signal_content']];
var today=new Date();
var hours = today.getHours();
var minutes = today.getMinutes();

var SPRNSTR="<!--startprint-->";//设置打印开始区域（在要打印的html上设置要打印的区域开始）
var EPRNSTR="<!--endprint-->";//设置打印结束区域（在要打印的html上设置要打印的区域结束）
// 打印页面数据
function printPage()
{
	// 打印设置
	var bdhtml=window.document.body.innerHTML;//获取当前页的html代码，用于保存原来的网页
	
	// 加上表格样式
	var prnhtml = '<style>.table{border-collapse:collapse; font-size:13px; height:20px; line-height:20px; background-color:#EFEFEF; text-align:left;}.table tr td{border:solid 1px #999999;}</style>';
	prnhtml +=bdhtml.substring(bdhtml.indexOf(SPRNSTR)+17); //从开始代码向后取html
	prnhtml=prnhtml.substring(0,prnhtml.indexOf(EPRNSTR));//从结束代码向前取html，这样就获取到了需要的局部页面
	
	
	var myWindow = window.open('','打印','');
	myWindow.document.write(prnhtml);
	myWindow.print();
	myWindow.close();
}

function getFormId(id) {
   if(id.length > 9 && id.substring(0 , 9) == 'plat_form') {
       return old_new_form_relative[id];
   }
   return id;
}
function getMyAttr(node , name) {
    if(node.attributes) {
        return node.attributes[name];
    }
    return node[name];
}
function addUrl(url) {
    var nowUrl = String(window.location);
    var splitIndex = nowUrl.indexOf("#");
    if(splitIndex > 0) {
        nowUrl = nowUrl.substring(0 , splitIndex);
    }
    window.location = nowUrl + "#" + url;
}
function addNewJS(jsurl) {
    if(!jsurl) return;
    jsurl = filerString(jsurl);
    if(jsList[jsurl]) return;
    if(jsurl.indexOf("?") != -1) {
    	jsurl += '&jsVersion=' + sys_js_version;
    }else {
    	jsurl += '?jsVersion=' + sys_js_version;
    }
    jsList[jsurl] = "1";
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = jsurl;
    oHead.appendChild(oScript);
}
function getURLKV(v) {
    var params = {};
    var paramsArray = v.split("&");
    forEach(paramsArray , function(param) {
        var paramNode = param.split("=");
        if(paramNode.length >= 2) {
            params[paramNode[0]] = paramNode[1];
        }
    });
    return params;
}
function toLocationPanel() {
    var nowUrl = String(window.location);
    var splitIndex = nowUrl.indexOf("#");
    if(splitIndex >= 0) {
         var params = nowUrl.substring(splitIndex + 1);
         var paramKV = getURLKV(params);
         param_pub_kv = paramKV;
         var toL = paramKV['location'];
         if(toL) {
              var platformPanel = Ext.getCmp(getFormId(toL));
              if(platformPanel) {
                  platformPanel.expand(true);
                  toOpenMenu(platformPanel , paramKV['menuId']);
              }
         }
    }
}
function toOpenMenu(platformPanel , menuId) {
    if(menuId) {
       ajax({
           url:PLAT_FORM + 'getOneMenu?menuId=' + menuId ,
           success:function(resp) {
               if(resp.responseText) {
                   var node = getJson(resp.responseText);
                   platformPanel.addOneNode(node);
               }
           }
       });
    }
}
var consoleFunctions = {
		addOneNodeCall: function(id , fn , t , title , refresh) {
		    if(t) id += t;
		    var console = Ext.getCmp(MAIN_CONSOLE);
		    var remote = Ext.getCmp(id);
		    if(remote != null && console.getEl(remote) != null) {
		        console.setActiveTab(remote);
		        if(refresh) remote.refresh();
		    }else {
		        if(t) {
		            var funcName = fn + "('" + t + "','" + title + "')";
		            remote = eval(funcName);
		        }else {
		            remote = eval(fn + "('" + title + "')");
		        }
		        remote.closable = true;
		        console.add(remote);
		        console.setActiveTab(remote);
		    }
		},
		addTempUrlPanel : function(url,title,id) {
		       var tempId = 'url_temp_' + id;
		       var console = Ext.getCmp(MAIN_CONSOLE);
		       var remote = Ext.getCmp(tempId);
		       if(remote == null || console.getEl(remote) == null) {
		           var htmlCode = '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + url + '"></iframe>';
		           remote = console.add({
		               id:tempId,border:false,title:title,closable:true,scripts:true,autoScroll:true,
		               discardUrl:true,nocache:true,timeout:9000,scope:this,html:htmlCode
		           });
		           console.setActiveTab(remote);
		       }else {
		           console.setActiveTab(remote);
		       }
		 },
		 newPanelShow : function(url , title) {
		        var htmlCode = '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + url + '"></iframe>';
		        var win = getEmptyPanel4([] , title, {
		           border:false,closable:true,scripts:true,region:'center',
		           discardUrl:true,nocache:true,timeout:9000,scope:this,html:htmlCode
		        } , 500 , 900 , null , true);
		        win.maximize();
		 },
		 addOneNode : function(node) {
		       var clickType = getMyAttr(node , 'clickType');
		       if(clickType == 1) {
		           var mutiObject = getMyAttr(node , 'mutiObject');
		           var type = (mutiObject == 1 ? getMyAttr(node , 'busiKey') : null);
		           consoleFunctions.addOneNodeCall(getMyAttr(node , 'objectId') , getMyAttr(node , 'functionName') , type ,
		               getMyAttr(node , 'text') , (getMyAttr(node , 'isRefresh') == 1));
		       }else if(clickType == 2) {//url
		           var url = getMyAttr(node ,'url');
		           var target = getMyAttr(node , 'target');
		           if(target == '_blank') {
		               window.open(url , node['text'] , 'height=650,width=1000,top=100,left=100,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no');
		           }else if(target == '_panel') {
		        	   consoleFunctions.newPanelShow(url , node['text']);
		           }else {
		        	   consoleFunctions.addTempUrlPanel(url,node['text'],getMyAttr(node , 'id'));
		           }
		       }
		   }
};
function toOpenMenuByMenuKey(wfKey , fn) {
	ajax({
		url:plat_url + 'getMenuByWfKey?wfKey=' + wfKey,
		success:function(resp) {
			if(resp.responseText) {
				var node = getJson(resp.responseText);
				consoleFunctions.addOneNode(node);
				if(fn) {
					fn.call(this , node['objectId']);
				}
			}
			else showTip('提示' , '流程配置出现问题，请联系相关技术人员解决.');
		}
	});
}
function getTargetName(target) {
    if(!target) target = 'default';
    return target_kv[target];
}
CMS.PlatFormMenuPanel = function(object ,staticPath) {
   var platformPanel = this , formId = object['sysName'];
   old_new_form_relative['plat_form' + object['id']] = formId;
   var rootNode = new Ext.tree.AsyncTreeNode({
        text:'功能列表',
        expanded:true
   });
   CMS.PlatFormMenuPanel.superclass.constructor.call(this, {
       id:formId,
       title:object['text'],
       autoScroll:true,
       animate:true,
       width:200,
       enableDD:false,
       containerScroll: false,
       rootVisible: false,
       iconCls:'userIcon',
       loader: new Ext.tree.TreeLoader({
            dataUrl :PLAT_FORM + 'getFavorite?allParentId=' + object['allParentId']
       }),
       root: rootNode,
       listeners:{
           'click':function(node,e) {
               addUrl("location=" + formId + "&menuId=" + node.attributes['id']);
               consoleFunctions.addOneNode(node);
           }
       }
   });
   platformPanel.on("load" , function(node) {
       if(isNaN(node.attributes['id'])) {
           node.expand(false , true , expandCallBack);
       }
   });

   var expandCallBack = function(node) {
       if(node.hasChildNodes()) {
           forEach(node.childNodes , function(nd) {
               if(!nd.isLeaf() && nd.attributes['expandChild'] == 1) {
                   nd.expand(false , true , expandCallBack);
               }
           });
       }
   };
   var jsFiles = object['jsFiles'];
   if(jsFiles) {
       var files = jsFiles.split(",");
       forEach(files , function(jsFile) {
           jsFile = jsFile.replace("$baseUrl$" , staticPath);
           addNewJS(jsFile);
       })
   }
};
Ext.extend(CMS.PlatFormMenuPanel, Ext.tree.TreePanel);

CMS.PlatHeaderPanel = function() {
	CMS.PlatHeaderPanel.superclass.constructor.call(this, {
		height:50,region:'north',xtype:"form",bodyStyle : "background:url('share/images/extend/f2.gif') repeat-x;",
		layout:"column",labelWidth:20,split:true,
		defaults:{
            columnWidth:0.3,layout:"form",hideLabels:true,border:false,bodyStyle:"padding:0px"
        },
        items:[{
            defaults:{xtype:"form",layout:"form",anchor:"100%",autoHeight:true,border:false,frame:false},columnWidth:0.7,
            items:[{
                autoHeight:true,defaults:{anchor:"-10"},bodyStyle : "background:url('share/images/extend/f2.gif') repeat-x;",
                html:'<img id ="CompanyLogo" src="share/images/login/logo.png" height="50"/>'
            }]
        },{
            defaults:{xtype:"form",layout:"form",anchor:"100%",autoHeight:true,border:false},
            items:[{
                autoHeight:true,defaults:{anchor:"-10"},bodyStyle : "background:url('share/images/extend/f2.gif') repeat-x;",
                html:'<div style="font-size:20ps" align="right">欢迎您，' 
                	+ login_user_name 
                	+ '[<a href="' + CONTEXT_PATH + '/login.jsp?loginout=true">退出</a>]，今天是'
                	+ today.getFullYear() + '年' + (today.getMonth()+1) + '月' + today.getDate() + '日'
                	//+ hours+':' + minutes 
                	+ '</div>'
            }]
        }]      
	});
};
Ext.extend(CMS.PlatHeaderPanel, Ext.Panel);

CMS.PlatStatusPanel = function() {
	CMS.PlatStatusPanel.superclass.constructor.call(this, {
		id:'status_bar',region:'south',xtype:"form",
		tbar:[
			{text:'退出系统',iconCls:'leftIcon',
				handler:function() {
					location.href = CONTEXT_PATH + '/login.jsp?loginout=true';
				}
			},'-',
			{xtype:"tbfill"},'-',
			{text:'与我联系',iconCls:'userIcon',
				handler:function() {
					showTip('与我联系' , '18615231992');
				}
			},'-',
			{text:'消息',iconCls:'userIcon',
				handler:function() {
					showNotification(search_base_url + 'getNotification');
				}
			},'-']
	});
};
Ext.extend(CMS.PlatStatusPanel, Ext.Panel);
var intervalId;
function showNotification(url){
    var notificationPanel = new CMS.NotificationListPanel(url);
    var win = new Ext.Window({
    	width:800,height:300,layout:'border',title:'通知列表',buttonAlign:'center',
    	items:[notificationPanel],
    	buttons:[{
    		text:'关 闭',handler:function() {
    			win.close();
    		}
    	}]
    });
    win.show();
    
    win.on('close', function(){
    	clearInterval(intervalId);
    });
}
var NOTIFICATION_PANEL;
CMS.NotificationListPanel = function(url) {
	NOTIFICATION_PANEL = this;
	var notificationObjArr = converArr([
	   	{name:'nid',width:50,header:'编号'},
	   	{name:'notice',width:480,header:'通知内容'},
		{name:'ntime',width:140,header:'时间'},
		{name:'nid' , width:80, header:'操作',renderer:function(v,c,row) {
			var data = row.data;
			var nid = data['nid'];
			var returnVal = "<a href=\"javascript:NOTIFICATION_PANEL.readed(" + nid + ")\">已读</a>";
		   	return returnVal;
		}}
	],true);
	var ds = getPageDs(url , 'nid' , notificationObjArr);
	CMS.NotificationListPanel.superclass.constructor.call(this, {
		region:'center',store:ds,view:getGridView('没有找到数据'),
		columns:notificationObjArr.columns,sm:getRowModel()
	});
	
	this.refresh = function() {
       ds.load();
    };
    
    this.refresh();
    
    //intervalId = setInterval("refreshNotificationPanel()",5000);
    
    this.readed = function(nid){
    	ajax({
    		url:search_base_url + 'readedNotification',
	    	params:{nid:nid},
		    success:function(resp) {
		    	NOTIFICATION_PANEL.refresh();
				ajaxSuc(resp);
			}
	    });
    }
};
Ext.extend(CMS.NotificationListPanel, Ext.grid.GridPanel);

function refreshNotificationPanel(){
	NOTIFICATION_PANEL.refresh();
}

var plat_url = CONTEXT_PATH + '/platform';
var sys_base_url = CONTEXT_PATH + "/system/sys";
var sys_basdata_url = CONTEXT_PATH + "/system/basdata";
var chg_base_url = CONTEXT_PATH + "/internal/chg";
var exchg_base_url = CONTEXT_PATH + "/external/chg";
var chg_hist_base_url = CONTEXT_PATH + "/search/hist";

var gender_data = [['1' , '男'] , ['2' , '女']];
var yes_or_no_data = [['1' , '是'] , ['2' , '否']];
var detail_row_css = [['plat_table_double','plat_table_double_content'] , ['plat_table_signal','plat_table_signal_content']];
function getClickType(clickType) {if(clickType == '1') return 'JS方法分派'; else if(clickType == '2') return '页面连接'; else return '无触发';}
function getnNormalConvName(muti) {return muti == '1' ? '是' : '否'}
function getMenuTypeKv(menuType) {return menuType == '1' ? '完全可见' : '仅DBA可见'}
function getTabDetailRowCss(row) {return detail_row_css[(row % 2)]}